package com.github.ilioili.justdoit.components.fragment;

import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.ilioili.justdoit.R;
import com.github.ilioili.justdoit.components.activity.CreateOrModifyActivity;
import com.github.ilioili.justdoit.components.activity.PickDateActivity;
import com.github.ilioili.justdoit.components.activity.PickTimeActivity;
import com.github.ilioili.justdoit.components.receiver.AlarmReceiver;
import com.github.ilioili.justdoit.model.dao.ScheduleEventDao;
import com.github.ilioili.justdoit.model.pojo.ScheduleEvent;
import com.github.ilioili.justdoit.util.CompatUtil;
import com.github.ilioili.justdoit.util.DateUtil;
import com.github.ilioili.justdoit.util.LanguageUtil;
import com.github.ilioili.justdoit.widget.SatelliteView;
import com.github.ilioili.justdoit.widget.WatchTimePicker;
import com.taihe.template.base.BaseFragment;
import com.taihe.template.base.injection.Id;
import com.taihe.template.base.injection.InjectionUtil;
import com.taihe.template.base.util.SizeUtil;
import com.taihe.template.base.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hantuo on 16/5/15.
 */
public class CategoryScheduleEventListFragment extends BaseFragment {
    private RecyclerView recyclerView;
    private List<ScheduleEvent> dataList = new ArrayList<>();
    private SatelliteMenu satelliteMenu;
    public static final int POSITION_NONE = -1;
    private int menuOpenedItemPosition = POSITION_NONE;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        initRecyclerView();
        return recyclerView;
    }

    private void initRecyclerView() {
        if (null == recyclerView) {
            recyclerView = new RecyclerView(getContext());
            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
            recyclerView.setHasFixedSize(false);
            recyclerView.setAdapter(new RecyclerView.Adapter<Holder>() {

                private int completeColor = CompatUtil.getColor(getContext(), R.color.font_light_gray);
                private int normalColor = CompatUtil.getColor(getContext(), R.color.font_normal);

                @Override
                public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
                    View view = LayoutInflater.from(getContext()).inflate(R.layout.category_to_do_item, parent, false);
                    return new Holder(view);
                }

                @Override
                public void onBindViewHolder(Holder holder, int position) {
                    ScheduleEvent dataItem = dataList.get(position);
                    holder.tvName.setText(dataItem.name);
                    holder.itemView.setTag(dataItem);
                    holder.tvName.setTag(dataItem);
                    holder.btnDelete.setTag(dataItem);
                    holder.btnComplete.setTag(dataItem);
                    holder.btnUndo.setTag(dataItem);
                    holder.btnArrange.setTag(dataItem);
                    holder.btnEditRoutine.setTag(dataItem);
                    holder.btnAlarm.setTag(dataItem);
                    setGone(holder.vMenu);

                    if (dataItem.isComplete) {
                        holder.tvName.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                        holder.tvName.setTextColor(completeColor);
                        holder.tvSub.setTextColor(completeColor);
//                        setGone(holder.btnComplete, holder.btnAlarm, holder.btnArrange, holder.btnDelete, holder.btnEditRoutine);
//                        setVisiable(holder.btnUndo);
                    } else {
                        holder.tvName.getPaint().setFlags(Paint.SUBPIXEL_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
//                        setVisiable(holder.btnComplete, holder.btnAlarm, holder.btnArrange, holder.btnDelete, holder.btnEditRoutine);
//                        setGone(holder.btnUndo);
                        holder.tvName.setTextColor(normalColor);
                        holder.tvSub.setTextColor(normalColor);
                    }

                    if (menuOpenedItemPosition == position) {
                        holder.vMenu.setVisibility(View.VISIBLE);
                    } else {
                        holder.vMenu.setVisibility(View.GONE);
                    }

                    String subInfo = null;
                    if (DateUtil.isBeforeToday(dataItem.startTime) && !dataItem.isComplete) {
                        subInfo = getResources().getString(R.string.delayer);
                    } else if (DateUtil.isToday(dataItem.startTime)) {
                        subInfo = getResources().getString(R.string.today);
                    } else if (DateUtil.isTomorrow(dataItem.startTime)) {
                        subInfo = getResources().getString(R.string.tomorrow);
                    } else if (DateUtil.isTheDayAfterTomorrow(dataItem.startTime)) {
                        subInfo = getResources().getString(R.string.day_after_tomorrow);
                    } else if (DateUtil.isThisWeek(dataItem.startTime)) {
                        subInfo = getResources().getString(R.string.this_week) + DateUtil.getWeekDay(getResources(), dataItem.startTime);
                    } else {
                        subInfo = DateUtil.getMonthDay(dataItem.startTime);
                    }
                    holder.tvSub.setText(subInfo);
                    if (dataItem.alarm) {
                        if (LanguageUtil.isChinese()) {
                            holder.tvSub.append("    提醒：" + dataItem.alermHour + "点" + dataItem.alermMinute + "分");
                        } else {
                            holder.tvSub.append("    Alarm：" + dataItem.alermHour + ":" + dataItem.alermMinute);
                        }
                    }
                }

                @Override
                public int getItemCount() {
                    return dataList.size();
                }
            });
            recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                        menuOpenedItemPosition = POSITION_NONE;
                    }
                }
            });
        }
    }


    public void loadData(final List<ScheduleEvent> scheduleEvents) {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                dataList.clear();
                dataList.addAll(scheduleEvents);
                recyclerView.getAdapter().notifyDataSetChanged();
                if (dataList.isEmpty()) {
                    setVisiable(R.id.no_task);
                } else {
                    setGone(R.id.no_task);
                }
            }
        });

    }


    @Override
    public void onPause() {
        super.onPause();
    }


    public static CategoryScheduleEventListFragment newInstance() {
        CategoryScheduleEventListFragment scheduleEventListFragment = new CategoryScheduleEventListFragment();
        return scheduleEventListFragment;
    }


    class Holder extends RecyclerView.ViewHolder {

        @Id(R.id.tv_name)
        TextView tvName;
        @Id(R.id.tv_sub)
        TextView tvSub;
        @Id(R.id.btn_delete)
        ImageView btnDelete;
        @Id(R.id.btn_done)
        ImageView btnComplete;
        @Id(R.id.btn_undo)
        ImageView btnUndo;
        @Id(R.id.btn_alarm)
        ImageView btnAlarm;
        @Id(R.id.btn_edit)
        ImageView btnEditRoutine;
        @Id(R.id.btn_arrange)
        ImageView btnArrange;
        @Id(R.id.content_view)
        View contentView;
        @Id(R.id.menu)
        View vMenu;


        public Holder(final View itemView) {
            super(itemView);
            InjectionUtil.loadView(itemView, this);
            btnComplete.setOnClickListener(onCompleteBtnClickListener);
            btnDelete.setOnClickListener(onDeleteBtnClickListener);
            btnUndo.setOnClickListener(onUndoBtnClickListener);
            btnAlarm.setOnClickListener(onAlarmBtnClickListener);
            btnEditRoutine.setOnClickListener(onEditBtnClickListener);
            btnArrange.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(final View v) {
//                    menuOpenedItemPosition = POSITION_NONE;
//                    recyclerView.getAdapter().notifyItemChanged(dataList.indexOf(itemView.getTag()));
                    recyclerView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (null == satelliteMenu) {
                                satelliteMenu = new SatelliteMenu();
                            }
                            satelliteMenu.show(v, (ScheduleEvent) v.getTag());
                        }
                    }, 200);

                }
            });
            CompatUtil.setFilterWithColorRes(R.color.font_gray, btnComplete, btnDelete, btnUndo, btnAlarm, btnEditRoutine, btnArrange);
            contentView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Object tag = itemView.getTag();
                    int curPosition = dataList.indexOf(tag);
                    if (curPosition == menuOpenedItemPosition) {
                        menuOpenedItemPosition = POSITION_NONE;
                    } else {
                        recyclerView.getAdapter().notifyItemChanged(menuOpenedItemPosition);
                        menuOpenedItemPosition = curPosition;
                    }
                    notifyItemChanged(tag);
                }
            });
        }

    }

    private final View.OnClickListener onAlarmBtnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(final View v) {
            final ScheduleEvent scheduleEvent = (ScheduleEvent) v.getTag();
            startActivity(PickTimeActivity.newIntent(getContext(), new WatchTimePicker.OnTimeSelectListener() {
                @Override
                public void onTimeSelected(int hour, int minute) {
                    scheduleEvent.alarm = true;
                    scheduleEvent.alermHour = hour;
                    scheduleEvent.alermMinute = minute;
                    ScheduleEventDao.replace(scheduleEvent);
                    AlarmReceiver.setAlarm(getContext().getApplicationContext(), scheduleEvent);
                    String tiemFragment;
                    if (LanguageUtil.isChinese()) {
                        if (hour < 5) {
                            tiemFragment = "凌晨";
                        } else if (hour < 8) {
                            tiemFragment = "早上";
                        } else if (hour < 12) {
                            tiemFragment = "上午";
                        } else if (hour < 18) {
                            tiemFragment = "下午";
                        } else if (hour < 23) {
                            tiemFragment = "晚上";
                        } else {
                            tiemFragment = "深夜";
                        }
                    } else {
                        tiemFragment = "";
                    }
                    recyclerView.getAdapter().notifyItemChanged(dataList.indexOf(scheduleEvent));
                    String hourStr = hour < 10 ? "0" + hour : "" + hour;
                    String minuteStr = minute < 10 ? "0" + minute : "" + minute;
                    Snackbar.make(v, getResources().getString(R.string.alarm_time_that_day) + tiemFragment + hourStr + ":" + minuteStr, Snackbar.LENGTH_LONG).show();
                }
            }));
        }
    };

    private void removeItemWithUiFresh(ScheduleEvent scheduleEvent) {
        int index = dataList.indexOf(scheduleEvent);
        dataList.remove(index);
        if (dataList.isEmpty()) {
            setVisiable(R.id.no_task);
        } else {
            setGone(R.id.no_task);
        }
        recyclerView.getAdapter().notifyItemRemoved(index);
    }

    private final View.OnClickListener onDeleteBtnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final ScheduleEvent scheduleEvent = (ScheduleEvent) v.getTag();
            String toast;
            if (LanguageUtil.isChinese()) toast = "删除\"" + scheduleEvent.name + "\"的所有记录吗";
            else toast = "Delete all records of \"" + scheduleEvent.name + "\" ?";
            Snackbar snackbar = Snackbar.make(v, toast, Snackbar.LENGTH_LONG);
            snackbar.setAction(R.string.confirm, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ScheduleEventDao.delete(scheduleEvent);
                    removeItemWithUiFresh(scheduleEvent);
                }
            });
            snackbar.show();
        }
    };

    private final View.OnClickListener onCompleteBtnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ScheduleEvent scheduleEvent = (ScheduleEvent) v.getTag();
            scheduleEvent.isComplete = true;
            ScheduleEventDao.replace(scheduleEvent);
            int index = dataList.indexOf(scheduleEvent);
            dataList.remove(index);
            dataList.add(scheduleEvent);
            recyclerView.getAdapter().notifyItemRemoved(index);
            recyclerView.getAdapter().notifyItemRangeInserted(dataList.size() - 1, 1);
            notifyItemChanged(scheduleEvent);
        }
    };

    private void notifyItemChanged(Object scheduleEvent) {
        recyclerView.getAdapter().notifyItemChanged(dataList.indexOf(scheduleEvent));
    }


    private final View.OnClickListener onUndoBtnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ScheduleEvent scheduleEvent = (ScheduleEvent) v.getTag();
            scheduleEvent.isComplete = false;
            ScheduleEventDao.replace(scheduleEvent);
            int index = dataList.indexOf(scheduleEvent);
            dataList.remove(index);
            recyclerView.getAdapter().notifyItemRemoved(index);
            dataList.add(0, scheduleEvent);
            recyclerView.getAdapter().notifyItemInserted(0);
            menuOpenedItemPosition = POSITION_NONE;
            notifyItemChanged(scheduleEvent);
        }
    };

    private final View.OnClickListener onEditBtnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ScheduleEvent scheduleEvent = (ScheduleEvent) v.getTag();
            int[] loc = new int[2];
            v.getLocationInWindow(loc);
            startActivity(CreateOrModifyActivity.newIntent(getContext(), scheduleEvent, loc[0] + v.getWidth() / 2, loc[1] + v.getHeight() / 2, scheduleEvent.color));
            getActivity().overridePendingTransition(0, 0);
        }
    };


    class SatelliteMenu {
        private ScheduleEvent scheduleEvent;
        private final View.OnClickListener onClickTodayListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                satelliteView.collapse();
                scheduleEvent.startTime = DateUtil.getTodayStartTime();
                ScheduleEventDao.replace(scheduleEvent);
                menuOpenedItemPosition = POSITION_NONE;
                notifyItemChanged(scheduleEvent);
            }
        };
        private final View.OnClickListener onClickOnedayLaterListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                satelliteView.collapse();
                scheduleEvent.startTime = Long.MAX_VALUE;
                ScheduleEventDao.replace(scheduleEvent);
                menuOpenedItemPosition = POSITION_NONE;
                notifyItemChanged(scheduleEvent);
            }
        };
        SatelliteView satelliteView;
        private final View.OnClickListener onClickThisWeekListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                satelliteView.collapse();
                if (DateUtil.isTheLastDayOfWeek(DateUtil.getTodayStartTime())) {
                    Snackbar snackbar = Snackbar.make(v, R.string.snack_push_to_next_week, Snackbar.LENGTH_LONG);
                    snackbar.setAction(R.string.confirm, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            scheduleEvent.startTime = DateUtil.getTodayStartTime() + 3 * DateUtil.DAY_MILISECOND;
                            ScheduleEventDao.replace(scheduleEvent);
                            menuOpenedItemPosition = POSITION_NONE;
                            notifyItemChanged(scheduleEvent);
                        }
                    });
                    snackbar.show();
                } else {
                    scheduleEvent.startTime = DateUtil.getTimeLaterInThisWeek(DateUtil.getTodayStartTime());
                    ScheduleEventDao.replace(scheduleEvent);
                    menuOpenedItemPosition = POSITION_NONE;
                    notifyItemChanged(scheduleEvent);
                }
            }
        };
        private final View.OnClickListener onDelayToDayClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                satelliteView.collapse();
                startActivity(PickDateActivity.newIntent(getContext(), new PickDateActivity.OnDateSelectListener() {
                    @Override
                    public void onDateSelect(int year, int month, int day) {
                        satelliteView.collapse();
                        if (DateUtil.isAfterToday(year, month, day)) {
                            scheduleEvent.startTime = DateUtil.getDayStartTime(year, month, day);
                            ScheduleEventDao.replace(scheduleEvent);
                            menuOpenedItemPosition = POSITION_NONE;
                            notifyItemChanged(scheduleEvent);
                        } else {
                            ToastUtil.showShortToast(getResources().getString(R.string.snack_push_to_today_or_future));
                        }
                    }
                }));
            }
        };


        private final View.OnClickListener onDelayToTheDayAfterTomorrowClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                satelliteView.collapse();
                scheduleEvent.startTime = DateUtil.getTodayStartTime() + 2 * DateUtil.DAY_MILISECOND;
                ScheduleEventDao.replace(scheduleEvent);
                menuOpenedItemPosition = POSITION_NONE;
                notifyItemChanged(scheduleEvent);
            }
        };
        private final View.OnClickListener onClickTororrowListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                satelliteView.collapse();
                scheduleEvent.startTime = DateUtil.getTodayStartTime() + DateUtil.DAY_MILISECOND;
                ScheduleEventDao.replace(scheduleEvent);
                menuOpenedItemPosition = POSITION_NONE;
                notifyItemChanged(scheduleEvent);
            }
        };
        private final View.OnClickListener onDelayInMonthClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                satelliteView.collapse();
                if (DateUtil.isTheLastDayOfMonth(DateUtil.getTodayStartTime())) {
                    Snackbar snackbar = Snackbar.make(v, R.string.snack_push_to_next_month, Snackbar.LENGTH_LONG);
                    snackbar.setAction(R.string.confirm, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            scheduleEvent.startTime = DateUtil.getTodayStartTime() + 7 * DateUtil.DAY_MILISECOND;
                            ScheduleEventDao.replace(scheduleEvent);
                            menuOpenedItemPosition = POSITION_NONE;
                            notifyItemChanged(scheduleEvent);
                        }
                    });
                    snackbar.show();
                } else {
                    scheduleEvent.startTime = DateUtil.getTimeLaterInThisMonth(DateUtil.getTodayStartTime());
                    ScheduleEventDao.replace(scheduleEvent);
                    menuOpenedItemPosition = POSITION_NONE;
                    notifyItemChanged(scheduleEvent);
                }
            }
        };

        private SatelliteMenu() {
            satelliteView = (SatelliteView) LayoutInflater.from(getContext()).inflate(R.layout.satellite_arrange_time_layout, null);
            satelliteView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    satelliteView.collapse();
                }
            });
            satelliteView.findViewById(R.id.d_calendar).setOnClickListener(onDelayToDayClickListener);
            satelliteView.findViewById(R.id.d_day_after_tomorrow).setOnClickListener(onDelayToTheDayAfterTomorrowClickListener);
            satelliteView.findViewById(R.id.d_tomorrow).setOnClickListener(onClickTororrowListener);
            satelliteView.findViewById(R.id.d_this_month).setOnClickListener(onDelayInMonthClickListener);
            satelliteView.findViewById(R.id.d_this_week).setOnClickListener(onClickThisWeekListener);
            satelliteView.findViewById(R.id.d_today).setOnClickListener(onClickTodayListener);
            satelliteView.findViewById(R.id.d_oneday).setOnClickListener(onClickOnedayLaterListener);
        }

        public void show(View v, ScheduleEvent scheduleEvent) {
            this.scheduleEvent = scheduleEvent;
            int[] loc = new int[2];
            v.getLocationOnScreen(loc);
            int top = (int) SizeUtil.pxToDp(loc[1], getContext());
            int bottom = (int) SizeUtil.pxToDp(getResources().getDisplayMetrics().heightPixels - loc[1], getContext());
            int start = 180;
            int radius = 110;
            if (top < 140) {
                start += 60;
                radius += radius / 2;
            }
            int end = 360;
            if (bottom < 100) {
                end -= 90;
                radius += radius;
            } else if (bottom < 160) {
                end -= 60;
                radius += radius / 2;
            }
            satelliteView.expand(v, SizeUtil.dpToPx(radius, getContext()), start, end);
        }
    }

}
